/*
 * Copyright 2014 http://Bither.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.photoeditor.demo.util;

import android.annotation.TargetApi;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.RegionIterator;
import android.os.Build;
import android.os.StrictMode;

import com.common.base.ComponentContext;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Class containing some static utility methods.
 */
public class Utils {
	private Utils() {
	};

	@TargetApi(11)
	public static void enableStrictMode() {
		if (Utils.hasGingerbread()) {
			StrictMode.ThreadPolicy.Builder threadPolicyBuilder = new StrictMode.ThreadPolicy.Builder()
					.detectAll().penaltyLog();
			StrictMode.VmPolicy.Builder vmPolicyBuilder = new StrictMode.VmPolicy.Builder()
					.detectAll().penaltyLog();

			if (Utils.hasHoneycomb()) {
				threadPolicyBuilder.penaltyFlashScreen();
				// TODO : Add our activities later
				// vmPolicyBuilder
				// .setClassInstanceLimit(ImageGridActivity.class, 1)
				// .setClassInstanceLimit(ImageDetailActivity.class, 1);
			}
			StrictMode.setThreadPolicy(threadPolicyBuilder.build());
			StrictMode.setVmPolicy(vmPolicyBuilder.build());
		}
	}

	public static boolean hasFroyo() {
		// Can use static final constants like FROYO, declared in later versions
		// of the OS since they are inlined at compile time. This is guaranteed
		// behavior.
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
	}

	public static boolean hasGingerbread() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
	}

	public static boolean hasHoneycomb() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
	}

	public static boolean hasHoneycombMR1() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
	}

	public static boolean hasICS() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
	}

	public static boolean hasJellyBean() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
	}

    public static byte[] readBytes(InputStream paramInputStream)
            throws IOException {
        byte[] arrayOfByte = new byte[paramInputStream.available()];
        paramInputStream.read(arrayOfByte);
        return arrayOfByte;
    }

    public static void copyStream(InputStream is, OutputStream os) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(os);
            byte[] bt = new byte[8192];
            int len = bis.read(bt);
            while (len != -1) {
                bos.write(bt, 0, len);
                len = bis.read(bt);
            }
            bis.close();
            bos.close();
        } catch (Exception e) {

            e.printStackTrace();
        } finally {

        }

    }

	public static boolean saveBitmap(Bitmap mBitmap, String savePath) {
		File filePic;
		try {
			filePic = new File(savePath);
			if (!filePic.exists()) {
				filePic.getParentFile().mkdirs();
				filePic.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(filePic);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	/**
	 * @return true-遮挡超过limit
	 */
	public static boolean oneRectOverlayAnotherInLimit(Rect rectF1, Rect rectF2, float limit) {
		Region region1 = new Region();
		region1.set(rectF1);

		Region region2 = new Region();
		Path path = new Path();
		path.moveTo(rectF2.left, rectF2.top);
		path.lineTo(rectF2.right, rectF2.top);
		path.lineTo(rectF2.right, rectF2.bottom);
		path.lineTo(rectF2.left, rectF2.bottom);
		path.lineTo(rectF2.left, rectF2.top);
		region2.setPath(path, region1);
		int area = calculateRegionArea(region2);

		if ((float)area / (rectF1.width() * rectF1.height()) >= limit) {
			//遮挡超过50%
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 计算region面积
	 * @param region
	 * @return
	 */
	public static int calculateRegionArea(Region region) {
		RegionIterator regionIterator = new RegionIterator(region);
		// amount of Rects
		int size = 0;
		// units of area
		float area = 0;
		Rect tmpRect= new Rect();
		while (regionIterator.next(tmpRect)) {
			size++;
			area += tmpRect.width() * tmpRect.height();
		}
		return (int) area;
	}

	private static final Pattern sIntegerPattern = Pattern.compile("(\\d+)");
	private static final Pattern sFloatPattern = Pattern.compile("(\\d+\\.\\d+)");

	public static boolean hasInteger(String str) {
		Matcher m = sIntegerPattern.matcher(str);
		return m.find();
	}

	public static Integer getOnlyInteger(String str) {
		List<Integer> list = new ArrayList<>();
		Matcher m = sIntegerPattern.matcher(str);
		String tmp = null;
		while (m.find()) {
			tmp = m.group();
			list.add(Integer.valueOf(tmp));
		}
		if (list.size() == 1 && list.get(0) != null) {
			return new Integer(list.get(0));
		} else {
			return null;
		}
	}

	public static Float getOnlyFloat(String string) {
		List<Float> list = new ArrayList<>();
		Matcher m = sFloatPattern.matcher(string);
		String tmp = null;
		while (m.find()) {
			tmp = m.group();
			list.add(Float.valueOf(tmp));
		}
		if (list.size() == 1 && list.get(0) != null) {
			return new Float(list.get(0));
		} else {
			return null;
		}
	}

	public static String getSystemLanguage() {
		Configuration configuration = ComponentContext.getContext().getResources().getConfiguration();
		return configuration.locale.getLanguage();
	}

}
